package org.transformatorhuis.unix.server.nativeos;

import org.transformatorhuis.unix.server.CloneableServer;
import org.transformatorhuis.unix.server.CommandLine;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

import static org.transformatorhuis.unix.server.THLibrary.THLIB;

/**
 * User: Olivier Van Acker
 * Date: Mar 15, 2010
 */
public class CommandLineLinux extends CommandLine {

    public CommandLineLinux() throws Exception {

        int pid = THLIB.getpid();

        try {
            String cmdline = readFile(new File("/proc/" + pid + "/cmdline"));
            for (String cmd : Arrays.asList(cmdline.split("\0")))
                add(cmd);
        } catch (IOException e) {

        }
        // we don't want them inherited
        removeSystemProperty(CloneableServer.class.getName());
    }

    /**
     * Reads the entire file.
     */
    private static String readFile(File f) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileInputStream fin = new FileInputStream(f);
        try {
            int sz;
            byte[] buf = new byte[1024];

            while((sz=fin.read(buf))>=0) {
                baos.write(buf,0,sz);
            }

            return baos.toString();
        } finally {
            fin.close();
        }
    }

}
